package com.company.calendar.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.company.calendar.dto.CompanyDTO;
import com.company.calendar.entity.Company;
import com.company.calendar.mapper.CompanyMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 公司服务类
 * 
 * @author System
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
@Transactional
public class CompanyService {
    
    private final CompanyMapper companyMapper;
    
    /**
     * 创建公司
     */
    public CompanyDTO createCompany(CompanyDTO companyDTO) {
        log.info("创建公司: {}", companyDTO.getCompanyName());
        
        // 检查公司编码是否已存在
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Company::getCompanyCode, companyDTO.getCompanyCode());
        
        if (companyMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("公司编码已存在: " + companyDTO.getCompanyCode());
        }
        
        Company company = new Company();
        company.setCompanyName(companyDTO.getCompanyName());
        company.setCompanyCode(companyDTO.getCompanyCode());
        company.setDescription(companyDTO.getDescription());
        
        companyMapper.insert(company);
        return convertToDTO(company);
    }
    
    /**
     * 根据ID获取公司信息
     */
    @Transactional(readOnly = true)
    public Optional<CompanyDTO> getCompanyById(Long id) {
        Company company = companyMapper.selectById(id);
        if (company == null || company.getIsDeleted()) {
            return Optional.empty();
        }
        return Optional.of(convertToDTO(company));
    }
    
    /**
     * 根据公司编码获取公司信息
     */
    @Transactional(readOnly = true)
    public Optional<CompanyDTO> getCompanyByCode(String companyCode) {
        Company company = companyMapper.findByCompanyCodeAndIsDeletedFalse(companyCode);
        if (company == null) {
            return Optional.empty();
        }
        return Optional.of(convertToDTO(company));
    }
    
    /**
     * 获取所有公司
     */
    @Transactional(readOnly = true)
    public List<CompanyDTO> getAllCompanies() {
        return companyMapper.findByIsDeletedFalse()
                .stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据公司名称模糊查询
     */
    @Transactional(readOnly = true)
    public List<CompanyDTO> searchCompaniesByName(String companyName) {
        return companyMapper.findByCompanyNameContaining(companyName)
                .stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 更新公司信息
     */
    public CompanyDTO updateCompany(Long id, CompanyDTO companyDTO) {
        log.info("更新公司信息: {}", id);
        
        Company company = companyMapper.selectById(id);
        if (company == null || company.getIsDeleted()) {
            throw new RuntimeException("公司不存在: " + id);
        }
        
        // 检查公司编码是否被其他公司使用
        if (!company.getCompanyCode().equals(companyDTO.getCompanyCode())) {
            LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Company::getCompanyCode, companyDTO.getCompanyCode())
                       .ne(Company::getId, id);
            
            if (companyMapper.selectCount(queryWrapper) > 0) {
                throw new RuntimeException("公司编码已存在: " + companyDTO.getCompanyCode());
            }
        }
        
        company.setCompanyName(companyDTO.getCompanyName());
        company.setCompanyCode(companyDTO.getCompanyCode());
        company.setDescription(companyDTO.getDescription());
        
        companyMapper.updateById(company);
        return convertToDTO(company);
    }
    
    /**
     * 删除公司（软删除）
     */
    public void deleteCompany(Long id) {
        log.info("删除公司: {}", id);
        
        Company company = companyMapper.selectById(id);
        if (company == null || company.getIsDeleted()) {
            throw new RuntimeException("公司不存在: " + id);
        }
        
        companyMapper.deleteById(id);
    }
    
    /**
     * 转换为DTO
     */
    private CompanyDTO convertToDTO(Company company) {
        CompanyDTO dto = new CompanyDTO();
        dto.setId(company.getId());
        dto.setCompanyName(company.getCompanyName());
        dto.setCompanyCode(company.getCompanyCode());
        dto.setDescription(company.getDescription());
        return dto;
    }
}


